// ===============================================
// primitive_utils
// 
// Create by Will on 2020/10/26 8:27 PM
// Copyright @data_food.All rights reserved.
// ===============================================

T findWithString<T>(Iterable<T> values, String match) {
  return values?.firstWhere(
        (value) => value.toString() == match,
    orElse: () => null,
  );
}

T firstOrNull<T>(Iterable<T> iterable) {
  if (iterable != null && iterable.isNotEmpty) {
    return iterable.first;
  } else {
    return null;
  }
}

T getOrNull<T>(Iterable<T> iterable, int index) {
  if (isEmptyIterable(iterable) == false &&
      index != null &&
      index < iterable.length) {
    if (iterable is List) {
      return (iterable as List)[index];
    } else {
      return iterable.elementAt(index);
    }
  } else {
    return null;
  }
}

bool isEmptyIterable(Iterable iterable) => iterable == null || iterable.isEmpty;

bool isBlankIterable(Iterable iterable) {
  if (isEmptyIterable(iterable)) {
    return true;
  }

  for (final e in iterable) {
    if (e != null) {
      return false;
    }
  }

  return true;
}

bool equalsIterable(Iterable a, Iterable b) {
  if (a == b) {
    return true;
  } else if (a?.length != b?.length) {
    return false;
  }

  final iteratorA = a.iterator;
  final iteratorB = b.iterator;
  while (iteratorA.moveNext()) {
    iteratorB.moveNext();
    if (iteratorA.current != iteratorB.current) {
      return false;
    }
  }

  return true;
}

extension BoolExt on bool {
  int toInt() => this ? 1 : 0;
}

extension IntExt on int {
  bool toBool() => this != 0;
}

extension StringExt on String {
  bool toBool() {
    return this != '0' && toLowerCase() != 'false';
  }

  // 抹除开头的0
  String stripLeadingZeros() {
    final pattern = RegExp(r'^0+');
    return replaceAll(pattern, "");
  }

  // 抹除末尾的0
  String stripTrailingZeros() {
    final pattern = RegExp(r'([.]{1}0*)(?!.*\d)');
    return replaceAll(pattern, "");
  }

  // 抹除非数字的字符
  String stripNotNum() {
    final pattern = RegExp(r'[^0-9]*');
    return replaceAllMapped(pattern, (match) => '');
  }

  String addCommasInNum() {
    final pattern = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
    return replaceAllMapped(pattern, (match) => '${match[1]},');
  }
}

extension IterableExt<T> on Iterable<T> {
  Iterable<T> divide(T divider) {
    return expand((child) sync* {
      yield divider;
      yield child;
    }).skip(1);
  }
}
